<template>
  <div class="rule-container">
    <!-- 当前启用的规则组 -->
    <div class="enabled-rules">
      <div class="header">
        <span class="title" style="font-size: 16px; font-weight: bold;">【当前启用的规则组】</span>
      </div>
      <a-table
        :columns="columns"
        :data-source="enabledRules"
        :loading="enabledLoading"
        :pagination="false"
        row-key="rule_id"
      >
        <template slot="weight" slot-scope="text, record">
          <div>
            <div>作者1：{{ record.author1_weight }}</div>
            <div v-if="record.author2_weight">作者2：{{ record.author2_weight }}</div>
            <div v-if="record.author3_weight">作者3：{{ record.author3_weight }}</div>
          </div>
        </template>
      </a-table>
    </div>

    <!-- 所有规则组 -->
    <div class="all-rules">
      <div class="header">
        <span class="title" style="font-size: 16px; font-weight: bold;">【所有规则组】</span>
        <a-button type="primary" icon="plus" @click="handleCreate">
          新增规则
        </a-button>
      </div>
      <div class="rule-groups">
        <div v-for="(group, index) in ruleGroups" :key="index" class="rule-group">
          <div class="group-header">
            <span class="group-title">规则组 {{ index + 1 }}</span>
            <a-button 
              type="primary" 
              :disabled="isGroupEnabled(index + 1)"
              @click="handleEnableGroup(index + 1)"
            >
              {{ isGroupEnabled(index + 1) ? '已启用' : '启用' }}
            </a-button>
          </div>
          <a-table
            :columns="columns"
            :data-source="group"
            :loading="loading"
            :pagination="false"
            row-key="rule_id"
          >
            <template slot="weight" slot-scope="text, record">
              <div>
                <div>作者1：{{ record.author1_weight }}</div>
                <div v-if="record.author2_weight">作者2：{{ record.author2_weight }}</div>
                <div v-if="record.author3_weight">作者3：{{ record.author3_weight }}</div>
              </div>
            </template>
            <template slot="action" slot-scope="text, record">
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除该规则吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" style="color: #ff4d4f">删除</a-button>
              </a-popconfirm>
            </template>
          </a-table>
        </div>
      </div>
    </div>

    <!-- 新增/编辑规则弹窗 -->
    <a-modal
      :visible="modalVisible"
      :title="modalType === 'create' ? '新增规则' : '编辑规则'"
      :confirmLoading="modalLoading"
      @ok="handleModalSubmit"
      @cancel="handleModalCancel"
    >
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-model-item label="规则组" prop="rule_group">
          <a-input-number 
            v-model="form.rule_group" 
            :min="1" 
            :max="99"
            style="width: 100%"
          />
        </a-form-model-item>
        <a-form-model-item label="作者人数" prop="num_authors">
          <a-select v-model="form.num_authors" @change="handleAuthorsChange">
            <a-select-option :value="1">1人</a-select-option>
            <a-select-option :value="2">2人</a-select-option>
            <a-select-option :value="3">3人</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="作者1权重" prop="author1_weight">
          <a-input-number 
            v-model="form.author1_weight"
            :min="0"
            :max="1"
            :step="0.1"
            style="width: 100%"
          />
        </a-form-model-item>
        <a-form-model-item 
          v-if="form.num_authors >= 2" 
          label="作者2权重" 
          prop="author2_weight"
        >
          <a-input-number 
            v-model="form.author2_weight"
            :min="0"
            :max="1"
            :step="0.1"
            style="width: 100%"
          />
        </a-form-model-item>
        <a-form-model-item 
          v-if="form.num_authors >= 3" 
          label="作者3权重" 
          prop="author3_weight"
        >
          <a-input-number 
            v-model="form.author3_weight"
            :min="0"
            :max="1"
            :step="0.1"
            style="width: 100%"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import {
  apiScoringRuleGetGroupList,
  apiScoringRuleCreate,
  apiScoringRuleUpdate,
  apiScoringRuleDelete,
  apiScoringRuleEnable,
  apiScoringRuleGetEnabled
} from '@/api/featch'

export default {
  name: 'Rule',
  data() {
    // 权重验证
    const validateWeights = (rule, value, callback) => {
      const { num_authors, author1_weight, author2_weight, author3_weight } = this.form
      const weights = [author1_weight]
      if (num_authors >= 2) weights.push(author2_weight)
      if (num_authors >= 3) weights.push(author3_weight)
      
      // 检查是否所有必填权重都已填写
      if (weights.some(w => w === undefined || w === null)) {
        callback(new Error('请填写所有作者的权重'))
        return
      }
      
      // 检查权重和是否为1
      const sum = weights.reduce((a, b) => a + b, 0)
      if (Math.abs(sum - 1) > 0.000001) {
        callback(new Error('所有作者权重之和必须等于1'))
        return
      }
      
      callback()
    }

    return {
      // 表格列配置
      columns: [
        { 
          title: '作者人数', 
          dataIndex: 'num_authors',
          width: 100
        },
        { 
          title: '作者1权重', 
          dataIndex: 'author1_weight',
          width: 120,
          customRender: (text) => text ? text.toFixed(1) : '-'
        },
        { 
          title: '作者2权重', 
          dataIndex: 'author2_weight',
          width: 120,
          customRender: (text) => text ? text.toFixed(1) : '-'
        },
        { 
          title: '作者3权重', 
          dataIndex: 'author3_weight',
          width: 120,
          customRender: (text) => text ? text.toFixed(1) : '-'
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ],
      
      // 数据
      ruleGroups: [],
      loading: false,
      enabledRules: [],
      enabledLoading: false,
      
      // 表单
      modalVisible: false,
      modalLoading: false,
      modalType: 'create', // create or edit
      form: {
        rule_id: undefined,
        rule_group: 1,
        num_authors: 1,
        author1_weight: 1,
        author2_weight: null,
        author3_weight: null
      },
      rules: {
        rule_group: [
          { required: true, message: '请输入规则组', trigger: 'blur' }
        ],
        num_authors: [
          { required: true, message: '请选择作者人数', trigger: 'change' }
        ],
        author1_weight: [
          { required: true, message: '请输入作者1权重', trigger: 'blur' },
          { validator: validateWeights, trigger: 'blur' }
        ],
        author2_weight: [
          { validator: validateWeights, trigger: 'blur' }
        ],
        author3_weight: [
          { validator: validateWeights, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getGroupList()
    this.getEnabledRules()
  },
  methods: {
    /**
     * @description 获取规则组列表
     */
    async getGroupList() {
      this.loading = true
      try {
        const res = await apiScoringRuleGetGroupList()
        if (res.code === 200) {
          this.ruleGroups = res.data
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.loading = false
    },

    /**
     * @description 获取启用的规则组
     */
    async getEnabledRules() {
      this.enabledLoading = true
      try {
        const res = await apiScoringRuleGetEnabled()
        if (res.code === 200) {
          this.enabledRules = res.data
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.enabledLoading = false
    },

    /**
     * @description 判断规则组是否启用
     */
    isGroupEnabled(groupId) {
      return this.enabledRules.some(rule => rule.rule_group === groupId)
    },

    /**
     * @description 启用规则组
     */
    async handleEnableGroup(groupId) {
      try {
        const res = await apiScoringRuleEnable({ rule_group: groupId })
        if (res.code === 200) {
          this.$message.success('启用成功')
          await this.getEnabledRules()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
    },

    /**
     * @description 打开新增弹窗
     */
    handleCreate() {
      this.modalType = 'create'
      this.modalVisible = true
      this.form = {
        rule_id: undefined,
        rule_group: 1,
        num_authors: 1,
        author1_weight: 1,
        author2_weight: null,
        author3_weight: null
      }
    },

    /**
     * @description 打开编辑弹窗
     */
    handleEdit(record) {
      this.modalType = 'edit'
      this.modalVisible = true
      this.form = { ...record }
    },

    /**
     * @description 作者人数改变
     */
    handleAuthorsChange(value) {
      // 重置权重
      this.form.author1_weight = 1
      this.form.author2_weight = null
      this.form.author3_weight = null
      
      if (value >= 2) {
        this.form.author1_weight = 0.6
        this.form.author2_weight = 0.4
      }
      if (value >= 3) {
        this.form.author1_weight = 0.5
        this.form.author2_weight = 0.3
        this.form.author3_weight = 0.2
      }
    },

    /**
     * @description 提交表单
     */
    handleModalSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.modalLoading = true
          try {
            const api = this.modalType === 'create' ? apiScoringRuleCreate : apiScoringRuleUpdate
            const res = await api(this.form)
            if (res.code === 200) {
              this.$message.success(this.modalType === 'create' ? '创建成功' : '更新成功')
              this.modalVisible = false
              await this.getGroupList()
              await this.getEnabledRules()
            } else {
              this.$message.error(res.message)
            }
          } catch (err) {
            this.$message.error(err.toString())
          }
          this.modalLoading = false
        }
      })
    },

    /**
     * @description 取消表单
     */
    handleModalCancel() {
      this.modalVisible = false
      this.$refs.form.resetFields()
    },

    /**
     * @description 删除规则
     */
    async handleDelete(record) {
      try {
        const res = await apiScoringRuleDelete({
          rule_id: record.rule_id
        })
        if (res.code === 200) {
          this.$message.success('删除成功')
          await this.getGroupList()
          await this.getEnabledRules()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
    }
  }
}
</script>

<style lang="less" scoped>
.rule-container {
  padding: 24px;
  background: #fff;

  .enabled-rules {
    margin-bottom: 24px;
    
    .header {
      margin-bottom: 16px;
      
      .title {
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  .all-rules {
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      .title {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .rule-groups {
      .rule-group {
        margin-bottom: 24px;
        
        .group-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          padding-bottom: 16px;
          border-bottom: 1px solid #f0f0f0;
          
          .group-title {
            font-size: 14px;
            font-weight: 500;
          }
        }
      }
    }
  }
}
</style>
